<template>
  <div class="fly-box" ref="fly-box">
    <svg :width="w" :height="h" :viewBox="`0 0 ${w} ${h}`">
      <defs>
        <path :id="pathId" :d="pathD" fill="none"></path>
        <!-- 动画渐变效果 -->
        <radialGradient :id="gradientId" r="50%" cx="50%" cy="50%" fx="100%" fy="50%">
          <stop offset="0%" stop-color="#fff" stop-opacity="1"></stop>
          <stop offset="100%" stop-color="#fff" stop-opacity="0"></stop>
        </radialGradient>
        <!-- 蒙版 -->
        <mask :id="maskId">
          <!-- 0,0坐标绘制一个圆 -->
          <circle :r="moveSize" cx="0" cy="0" :fill="`url(#${gradientId})`">
            <!-- 围绕多边形做轨迹动画 -->
            <animateMotion
              :dur="dur"
              :path="pathD"
              rotate="auto"
              repeatCount="indefinite"
            ></animateMotion>
          </circle>
        </mask>
      </defs>
      <use :href="`#${pathId}`" stroke-width="0" stroke="#235fa7"></use>
      <use
        :href="`#${pathId}`"
        stroke-width="15"
        :stroke="moveColor"
        :mask="`url(#${maskId})`"
      ></use>
    </svg>
    <div class="fly-box-content">
      <slot></slot>
    </div>
  </div>
</template>

<script type="text/ecmascript-6">
import { getCurrentInstance, onMounted, ref } from 'vue';
import { uuid } from '@/utils';

export default {
	name : 'flyBox',
	props : {
		dur : { // 动画时间
			type : [Number,String],
			default : 5,
		},
		moveSize : { // 动画轨迹的大小
			type : [Number,String],
			default : 100,
		},
		moveColor : { // 动画轨迹的颜色
			type : String,
			default : '#c5fb79',
		},
	},
	setup () {
		let w = ref(0);
		let h = ref(0);
		let pathId = ref(`fly-box-path-${uuid()}`);
		let gradientId = ref(`fly-box-gradient-${uuid()}`);
		let maskId = ref(`fly-box-mask-${uuid()}`);
		let pathD = ref('');
		onMounted(()=>{
			let	dom = getCurrentInstance().ctx.$refs['fly-box'];
			w.value = dom.clientWidth;
			h.value = dom.clientHeight;
			pathD.value = `M0 0 L${w.value} 0 L${w.value} ${h.value} L0 ${h.value} Z`;
		});
		return {
			w,
			h,
			pathId,
			gradientId,
			maskId,
			pathD
		};
	}
};
</script>

<style lang="scss" scoped>
.fly-box {
  position: relative;
  height: 100%;
  width: 100%;
  svg {
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
  }
  .fly-box-content {
    height: 100%;
    width: 100%;
  }
}
</style>
